package com.example.bicycle.handler.mybatis;

import com.example.bicycle.domain.enums.UserTypeEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户类型枚举的自定义类型处理器
 * 专门处理PostgreSQL的user_type_enum类型
 */
@MappedTypes(UserTypeEnum.class)
public class UserTypeEnumTypeHandler extends BaseTypeHandler<UserTypeEnum> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, UserTypeEnum parameter, JdbcType jdbcType) throws SQLException {
        // 将枚举值作为字符串写入数据库
        ps.setObject(i, parameter.getValue(), java.sql.Types.OTHER);
    }

    @Override
    public UserTypeEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (value == null) {
            return null;
        }
        return UserTypeEnum.fromValue(value);
    }

    @Override
    public UserTypeEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        if (value == null) {
            return null;
        }
        return UserTypeEnum.fromValue(value);
    }

    @Override
    public UserTypeEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        if (value == null) {
            return null;
        }
        return UserTypeEnum.fromValue(value);
    }
} 